package com.ag.main.v1;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

public class ImageWriter {
    private static final int LSB_MASK = 0xFE; // 用于清除最低有效位的掩码
    // 将字母隐藏在指定的图片中
    public static void hideMessageInImage(File imageFile, String message) throws Exception {
        // 读取图片
        BufferedImage image = ImageIO.read(imageFile);
        int width = image.getWidth();
        int height = image.getHeight();
        //把要隐藏的信息转为字符数组
        char[] messageArray= message.toCharArray();
        int messageLength = messageArray.length;
        int messageIndex = 0;
        // 遍历每个像素
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                Color color = new Color(image.getRGB(x, y));
                int red = color.getRed();
                int green = color.getGreen();
                int blue = color.getBlue();
                // 如果还有未隐藏的信息，则将信息隐藏在RGB的最低有效位上
                if (messageIndex < messageLength) {
                    //每写入一个就判断一次是否还有为隐藏的信息
                    int bin = Integer.parseInt(String.valueOf(messageArray[messageIndex++]));
                    red = (red & LSB_MASK) | bin;
                    if (messageIndex < messageLength) {
                        bin = Integer.parseInt(String.valueOf(messageArray[messageIndex++]));
                        green = (green & LSB_MASK) | bin;
                    }
                    if (messageIndex < messageLength) {
                        bin = Integer.parseInt(String.valueOf(messageArray[messageIndex++]));
                        blue = (blue & LSB_MASK) | bin;
                    }
                }
                // 将修改后的RGB值写回图片
                Color newColor = new Color(red, green, blue);
                image.setRGB(x, y, newColor.getRGB());
            }
        }
        // 将修改后的图片保存到文件
        File outputFile = new File("output/"+imageFile.getName());
        ImageIO.write(image, "png", outputFile);
        System.out.println("信息已成功隐藏在图片中。");
    }

    public static void main(String[] args) throws Exception {
        // 指定要隐藏信息的图片和要隐藏的信息
        File imageFile = new File("./static/33.png");
        //A的二进制
        String message = "01000001";
        // 将信息隐藏在图片中
        hideMessageInImage(imageFile, message);
    }
}
